package com.ruoyi.project.api.cat;

import com.google.common.collect.Lists;
import com.ruoyi.project.api.cat.vo.CatVo;
import com.ruoyi.project.system.cat.domain.Cat;
import com.ruoyi.project.system.cat.service.impl.CatServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CatApiService {

    final CatServiceImpl catService;

    @Autowired
    public CatApiService(CatServiceImpl catService) {
        this.catService = catService;
    }


    /**
     * 获取树状目录结构
     */
    public List<CatVo> getCatTree() {
        List<Cat> cats = this.catService.selectCatList(null);
        List<CatVo> catVos = cats.stream()
                .map(cat -> convertCat(cat))
                .collect(Collectors.toList());

        List<CatVo> tree = catVos.stream()
                .filter(catVo -> catVo.getParent_id() == 0)
                .map(catVo -> {
                    getChild(catVo, catVos);
                    return catVo;
                })
                .collect(Collectors.toList());
        return tree;
    }


    /**
     * 递归获取树形结构
     * @param rootCatVo     根节点
     * @param catVos        子节点列表
     */
    private void getChild(CatVo rootCatVo, List<CatVo> catVos) {
        List<CatVo> child = Lists.newArrayList();
        catVos.stream()
                .filter(item -> item.getParent_id() == rootCatVo.getId())
                .forEach(item -> {
                    child.add(item);
                    getChild(item, catVos);
                });
        rootCatVo.set_child(child);
    }


    /**
     * 转换实体类型为Vo
     */
    private CatVo convertCat(Cat cat) {
        CatVo catVo = new CatVo();
        catVo.setId(cat.getId());
        catVo.setCat_name(cat.getCatName());
        catVo.setParent_id(cat.getParentId());
        catVo.setSort(cat.getSort());
        return catVo;
    }

}
